package org.grow.authfilter.service;


import org.grow.authfilter.entity.RoleInfo;
import org.grow.authfilter.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * @Author: xwg
 * @CreateDate: 21-7-15
 */

@Service
public class UserInfoService
        implements UserDetailsService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        String sql1 = "select * from UserInfo where username = ?";
        List<UserInfo> query = jdbcTemplate.query(sql1, new BeanPropertyRowMapper<>(UserInfo.class), s);
        if (query.size() == 0) throw new UsernameNotFoundException("用户名不存在");
        UserInfo userInfo = query.get(0);
        String sql2 = "select r.* from UserInfo u\n" +
                "            inner join UserRole ur on u.userId = ur.userFk\n" +
                "            inner join RoleInfo r on ur.roleFk = r.roleId\n" +
                "            where u.username = ?";
        List<RoleInfo> roles = jdbcTemplate.query(sql2, new BeanPropertyRowMapper<>(RoleInfo.class), s);
        if (CollectionUtils.isEmpty(roles)) {
            userInfo.setAuthorities(Collections.emptyList());
        } else {

            userInfo.setAuthorities(roles);
        }
        System.out.println("身份认证：数据库查询到的：" + userInfo);
        return userInfo;
    }
}
